package com.spaceobj.chess.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spaceobj.chess.entity.Game;
import com.spaceobj.chess.entity.GameChatInfo;
import com.spaceobj.chess.entity.Move;
import com.spaceobj.chess.entity.Replay;
import com.spaceobj.chess.entity.Spectator;
import com.spaceobj.chess.entity.User;
import com.spaceobj.chess.mapper.GameChatInfoMapper;
import com.spaceobj.chess.mapper.GameMapper;
import com.spaceobj.chess.mapper.MoveMapper;
import com.spaceobj.chess.mapper.ReplayMapper;
import com.spaceobj.chess.mapper.SpectatorMapper;
import com.spaceobj.chess.mapper.UserMapper;

@Service
public class MySQLService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GameMapper gameMapper;
    @Autowired
    private MoveMapper moveMapper;
    @Autowired
    private ReplayMapper replayMapper;
    @Autowired
    private GameChatInfoMapper chatMapper;
    @Autowired
    private SpectatorMapper spectatorMapper;

    // 用户信息管理
    public void saveUser(User user) {
        userMapper.insert(user);
    }

    public User getUser(Integer userId) {
        return userMapper.selectById(userId);
    }

    // 游戏记录管理
    public void saveGame(Game game) {
        gameMapper.insert(game);
    }

    public Game getGame(Integer gameId) {
        return gameMapper.selectById(gameId);
    }

    // 走棋记录管理
    public void saveMove(Move move) {
        moveMapper.insert(move);
    }

    public List<Move> getGameMoves(Integer gameId) {
        LambdaQueryWrapper<Move> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Move::getGameId, gameId);
        wrapper.orderByAsc(Move::getMoveId);
        return moveMapper.selectList(wrapper);
    }

    // 回放数据管理
    public void saveReplay(Replay replay) {
        replayMapper.insert(replay);
    }

    public Replay getReplay(Integer gameId) {
        return replayMapper.selectById(gameId);
    }

    // 聊天记录管理
    public void saveChat(GameChatInfo chat) {
        chatMapper.insert(chat);
    }

    public List<GameChatInfo> getGameChats(Integer gameId) {
        LambdaQueryWrapper<GameChatInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GameChatInfo::getGameId, gameId);
        wrapper.orderByAsc(GameChatInfo::getChatTime);
        return chatMapper.selectList(wrapper);
    }

    // 观战记录管理
    public void saveSpectator(Spectator spectator) {
        spectatorMapper.insert(spectator);
    }

    public List<Spectator> getGameSpectators(Integer gameId) {
        LambdaQueryWrapper<Spectator> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Spectator::getGameId, gameId);
        wrapper.orderByAsc(Spectator::getJoinedAt);
        return spectatorMapper.selectList(wrapper);
    }
} 